<template>
  <BaseDrawer
    :visible="visible"
    :title="`设置角色权限 - ${roleData?.roleName || ''}`"
    size="80%"
    direction="rtl"
    footer-type="default"
    confirm-text="保存权限"
    cancel-text="取消"
    :confirm-loading="loading"
    @update:visible="handleUpdateVisible"
    @confirm="handleSave"
    @cancel="handleCancel"
  >
    <div class="permissions-container">
      <div class="permissions-grid">
        <!-- 菜单权限 -->
        <div class="permission-panel">
          <MenuPermissions
            v-model="permissions.pagePrivilege"
            :menu-data="menuData"
          />
        </div>
        
        <!-- 摄像机权限 -->
        <div class="permission-panel">
          <CameraPermissions
            ref="cameraPermissionsRef"
            v-model="permissions.cameraPrivileges"
            :camera-data="cameraData"
          />
        </div>
        
        <!-- NMC权限 -->
        <div class="permission-panel">
          <NMCPermissions
            v-model="permissions.nmcPrivilege"
            :nmc-data="nmcData"
          />
        </div>
      </div>
    </div>
  </BaseDrawer>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { api } from '@/api'
import { $getAllServer } from '@/api/nvr'
import { success, error } from '@/utils/toast'
import BaseDrawer from '@/components/BaseDrawer.vue'
import MenuPermissions from './MenuPermissions.vue'
import CameraPermissions from './CameraPermissions.vue'
import NMCPermissions from './NMCPermissions.vue'
import { MENU_PERMISSIONS } from '@/types'
import type { StreamServer } from '@/types'

// Props
interface Props {
  visible: boolean
  roleData?: any
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  roleData: () => null
})

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'success': []
}>()

// 响应式数据
const loading = ref(false)
const cameraPermissionsRef = ref()

// 权限数据
const permissions = reactive({
  pagePrivilege: [] as string[], // 页面权限ID数组
  subPagePrivilege: [] as string[],
  nmcPrivilege: [] as string[],
  cameraPrivileges: [] as any[]
})

// 模拟数据（实际项目中应该从API获取）
const menuData = ref([])
const cameraData = ref([])
const nmcData = ref<StreamServer[]>([])

// 计算属性
const roleId = computed(() => props.roleData?.roleId)

// 监听器
watch(
  () => props.visible,
  async (val) => {
    if (val && props.roleData) {
      // 打开时重新加载数据
      await loadRolePermissions()
    } else if (!val) {
      // 关闭时清空数据
      clearAllData()
    }
  }
)

// watch(
//   () => props.roleData,
//   (newData) => {
//     if (newData && props.visible) {
//       loadRolePermissions()
//     }
//   }
// )

// 加载NMC数据
const loadNMCData = async () => {
  try {
    const response = await $getAllServer(2) // type=2 表示NMC数据
    nmcData.value = response.data || []
  } catch (error) {
    console.error('加载NMC数据失败:', error)
    nmcData.value = []
  }
}

// 加载角色权限（从角色数据中直接获取）
const loadRolePermissions = async () => {
  if (!props.roleData) return
  
  try {
    loading.value = true
    
    // 并行加载NMC数据
    await loadNMCData()
    
    // 直接从角色数据中获取权限信息
    const roleData = props.roleData
    
    // 处理页面权限
    if (roleData.pagePrivilege) {
      if (roleData.pagePrivilege === '-1' || roleData.pagePrivilege === -1) {
        // 如果是-1，表示拥有所有页面权限
        const configurablePermissions = getAllConfigurablePermissions()
        permissions.pagePrivilege = configurablePermissions.map(p => p.id)
      } else {
        // 其他情况都转换为ID数组
        permissions.pagePrivilege = convertCodeToPagePrivilege(roleData.pagePrivilege)
      }
    } else {
      permissions.pagePrivilege = []
    }
    
    // 处理子页面权限
    permissions.subPagePrivilege = roleData.subPagePrivilege || []
    
    // 处理NMC权限（字符串格式，如 "1,2,3"）
    if (roleData.nmcPrivilege) {
      if (typeof roleData.nmcPrivilege === 'string') {
        // 如果是字符串，按逗号分割转换为数组
        permissions.nmcPrivilege = roleData.nmcPrivilege.split(',').filter(Boolean)
      } else if (Array.isArray(roleData.nmcPrivilege)) {
        permissions.nmcPrivilege = roleData.nmcPrivilege
      } else {
        permissions.nmcPrivilege = []
      }
    } else {
      permissions.nmcPrivilege = []
    }
    
    // 处理摄像头权限
    permissions.cameraPrivileges = roleData.cameraPrivileges || []
    
  } catch (err) {
    console.error('加载角色权限失败:', err)
    error('加载角色权限失败')
  } finally {
    loading.value = false
    
    // 重新加载摄像机权限组件的数据
    // 延迟调用确保组件已经完全渲染
    setTimeout(() => {
      if (cameraPermissionsRef.value && cameraPermissionsRef.value.reloadData) {
        cameraPermissionsRef.value.reloadData()
      }
    }, 100)
  }
}

// 获取所有可配置的权限
const getAllConfigurablePermissions = (): any[] => {
  const configurablePermissions: any[] = []
  
  const extractConfigurable = (permissions: any[]) => {
    permissions.forEach(permission => {
      if (permission.isConfigurable && permission.code) {
        configurablePermissions.push(permission)
      }
      if (permission.children) {
        extractConfigurable(permission.children)
      }
    })
  }
  
  extractConfigurable(MENU_PERMISSIONS)
  return configurablePermissions
}

// 将页面权限ID转换为权限码
const convertPagePrivilegeToCode = (pageIds: string[]): number => {
  const configurablePermissions = getAllConfigurablePermissions()
  
  // 按位运算计算权限码，不转换为-1
  let code = 0
  pageIds.forEach(id => {
    const permission = configurablePermissions.find(p => p.id === id)
    if (permission && permission.code) {
      code |= permission.code
    }
  })
  return code
}

// 将权限码转换为页面权限ID
const convertCodeToPagePrivilege = (code: number | string): string[] => {
  const pageIds: string[] = []
  const configurablePermissions = getAllConfigurablePermissions()
  
  // 转换为数字类型
  const numericCode = typeof code === 'string' ? parseInt(code, 10) : code
  
  // 如果权限码为-1，表示拥有所有页面权限
  if (numericCode === -1) {
    return configurablePermissions.map(p => p.id)
  }
  
  configurablePermissions.forEach(permission => {
    if (permission.code && (numericCode & permission.code)) {
      pageIds.push(permission.id)
    }
  })
  
  return pageIds
}

// 保存权限
const handleSave = async () => {
  if (!roleId.value) return
  
  // 验证页面权限：必须至少选择一个页面权限
  const configurablePermissions = getAllConfigurablePermissions()
  const selectedConfigurablePermissions = permissions.pagePrivilege.filter(id => 
    configurablePermissions.some(p => p.id === id)
  )
  
  if (selectedConfigurablePermissions.length === 0) {
    error('请至少选择一个页面权限')
    return
  }
  
  try {
    loading.value = true
    
    // 准备保存的数据
    const saveData: any = {
      roleId: roleId.value,
      roleName: props.roleData.roleName
    }
    
    // 页面权限：有权限就传权限码，没有权限就传null
    const currentPagePrivilege = convertPagePrivilegeToCode(permissions.pagePrivilege)
    saveData.pagePrivilege = currentPagePrivilege > 0 ? currentPagePrivilege.toString() : null
    
    // 子页面权限直接设置为null
    saveData.subPagePrivilege = null
    
    // NMC权限：有权限就传权限字符串，没有权限就传null
    saveData.nmcPrivilege = permissions.nmcPrivilege.length > 0 ? permissions.nmcPrivilege.join(',') : null
    
    // 摄像机权限：有权限就传权限数组，没有权限就传null
    saveData.cameraPrivileges = permissions.cameraPrivileges.length > 0 ? permissions.cameraPrivileges : null
    
    
    await api.role.updateRoleData(saveData)
    success('权限设置成功')
    emit('success')
    handleCancel()
  } finally {
    loading.value = false
  }
}

// 处理抽屉显示状态更新
const handleUpdateVisible = (value: boolean) => {
  emit('update:visible', value)
}

// 清空所有数据
const clearAllData = () => {
  // 重置权限数据
  permissions.pagePrivilege = []
  permissions.subPagePrivilege = []
  permissions.nmcPrivilege = []
  permissions.cameraPrivileges = []
  
  // 清空其他数据
  menuData.value = []
  cameraData.value = []
  nmcData.value = []
  
  // 清空摄像机权限组件的内部状态
  if (cameraPermissionsRef.value && cameraPermissionsRef.value.clearAllData) {
    cameraPermissionsRef.value.clearAllData()
  }
}

// 取消操作
const handleCancel = () => {
  clearAllData()
  emit('update:visible', false)
}
</script>

<style scoped>
.permissions-container {
  height: 100%;
  padding: 0;
}

.permissions-grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 20px;
  height: 100%;
  min-height: 600px;
}

.permission-panel {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background: #fff;
  overflow: hidden;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .permissions-grid {
    grid-template-columns: 1fr 1fr;
    grid-template-rows: 1fr 1fr;
  }
  
  .permission-panel:last-child {
    grid-column: 1 / -1;
  }
}

@media (max-width: 768px) {
  .permissions-grid {
    grid-template-columns: 1fr;
    grid-template-rows: repeat(3, 1fr);
  }
  
  .permission-panel:last-child {
    grid-column: 1;
  }
}
</style>
